<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Validator;

use App\Http\Models\ProjectModel;
use App\Http\Models\MusicModel;
use App\Http\Models\MusicRelationModel;

class AudioController extends HomeController
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */

	/*获取通用模版背景音乐列表和当前项目的背景音乐*/
    public function list(Request $request)
    {
		try{
            $this->validate($request, [
                'apptoken' => 'required'
            ]);
            $apptoken = $request->input('apptoken');
            $project_info = ProjectModel::info($apptoken);
            $relationInfo = MusicRelationModel::getMusicId($project_info->id);
            $list = MusicModel::getDefaultList();
			if($relationInfo) {
            	$musicInfo =  MusicModel::info($relationInfo->music_id);
            	$musicInfo->is_select = 1;

            	// get_bgmusic_url($)
            	$list = array_unshift($list, $musicInfo);
			}
            return response()->json(build_result(["info"=>build_bgmusic_info($list)]));
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001',$e->getFile() . $e->getLine() . $e->getMessage()));
        }
        
    }

	/*
 	 * 设置背景音乐  判断是否修改，如果修改则需要替换音乐文件
 	 */
    public function setbgmusic(Request $request)
	{
        try{
            $this->validate($request, [
                'apptoken'  => 'required',
                'musicid'   => 'required',
                'musicpath' => 'required'
            ]);
            $apptoken = $request->input('apptoken');
            $musicid = $request->input('musicid');

            $musicid = (int)$musicid;
            if($musicid <= 0) {
                return response()->json(build_result('', '10001'));
            }

            // 获取当前Token对应的musicid
            $project_info = ProjectModel::info($apptoken);
            $relationInfo = MusicRelationModel::getMusicId($project_info->id);

            if($relationInfo->music_id == $musicid) {
                return response()->json(build_result(["info" => $musicid]));
            }

            $musicInfo = MusicModel::info($relationInfo->music_id);

            $newMusicpath = get_resource_dir() . '/' . $musicInfo->path;
            $destPath = get_app_dir($apptoken) . '/' . $musicpath;

            if(file_exists($newMusicpath)) {
                copy($newMusicpath, $destPath);
            }
            return response()->json(build_result(["info" => $musicid]));
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }



	}
}
